﻿namespace GameLib.Games.Components
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using GameLib.Games.Util;

    public class ModConflictHandler<T> : AbstractModMatcherHandler<T> where T : IMod
    {
        public override ModMatcherHandlerAction Handle(IModMatcher matcher, T mod)
        {
            ModMatcherHandlerEventArgs eventArgs = new ModMatcherHandlerEventArgs(mod);

            OnBeforeHandleEvent(eventArgs);

            if (eventArgs.Action == null)
            {
                switch (this.displayMessage(matcher, mod))
                {
                    case DialogResult.Yes:
                        eventArgs.Action = ModMatcherHandlerAction.DisableMatchingMod;
                        break;
                    case DialogResult.No:
                        eventArgs.Action = ModMatcherHandlerAction.DisableMod;
                        break;
                    default:
                        eventArgs.Action = ModMatcherHandlerAction.DoNothing;
                        break;
                }
            }

            if (eventArgs.Handle)
            {
                switch (eventArgs.Action)
                {
                    case ModMatcherHandlerAction.DisableMatchingMod:
                        mod.Owner.DisableMod(mod);
                        break;
                    case ModMatcherHandlerAction.DisableMod:
                        matcher.Owner.Owner.DisableMod(matcher.Owner);
                        break;
                }
                eventArgs.Handled = true;
            }

            OnAfterHandleEvent(eventArgs);

            return eventArgs.Action;
        }

        private DialogResult displayMessage(IModMatcher matcher, T mod)
        {
            string message = matcher.Owner.Name + " conflicts with active mod " + mod.Name + "(" + mod.Id + ").";
            if (!string.IsNullOrEmpty(matcher.Message))
            {
                message += "\n\nDetails:\n" + matcher.Message;
            }

            message += "\n\nWould you like to disable the conflicting mod?\n";
            message += "\n    Press Yes to disable " + mod.Name;
            message += "\n    Press No to disable " + matcher.Owner.Name;
            message += "\n    Press Cancel to leave both mods active, ignoring this conflict";

            string title = matcher.Owner.Name + " - Conflict";

            return MessageBox.Show(message, title, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
        }
    }
}
